
#include "Base.h"

#include "ComponentManager.h"
#include "BaseEntity.h"
#include "Component.h"
#include "ContainerUtil.h"
#include "EventHandler/EventHandler.h"
#include "Assert.h"

#include <Memory/DebugNew.h>

namespace CasaEngine
{

	/**
	 * 
	 */
	ComponentManager::ComponentManager(BaseEntity* pEntity_)
	{
		CASAENGINE_ASSERT(pEntity_ != NULL && "ComponentManager::ComponentManager() : BaseEntity is NULL");

		m_pEntity = pEntity_;
	}

	/**
	 * 
	 */
	ComponentManager::~ComponentManager()
	{
		DeleteSTLContainer(m_Components);
	}

	/**
	 * 
	 */
	BaseEntity* ComponentManager::GetEntity() const 
	{ 
		return m_pEntity; 
	}

	/**
	 * 
	 */
	void  ComponentManager::Update(const GameTime& gameTime_)
	{
		for (size_t i=0; i<m_Components.size(); i++)
		{
			m_Components[i]->Update(gameTime_);
		}
	}

	/**
	 * 
	 */
	void ComponentManager::HandleEvent(const Event* pEvent_)
	{
		for (size_t i=0; i<m_Components.size(); i++)
		{
			m_Components[i]->OnFPSChange(pEvent_);
		}
	}

	/**
	 * 
	 */
	void ComponentManager::Write(std::ostream& /*os*/) const
	{

	}

	/**
	 * 
	 */
	void ComponentManager::Read (std::ifstream& /*is*/)
	{

	}

	/**
	 * 
	 */
	void ComponentManager::AddComponent( Component* m_pComponent_ )
	{
		CASAENGINE_ASSERT(m_pComponent_ != NULL && "ComponentManager::AddComponent() : Component is NULL");

		m_Components.push_back(m_pComponent_);
	}

	/**
	 * 
	 */
	void ComponentManager::RemoveComponent( Component* m_pComponent_ )
	{
		CASAENGINE_ASSERT(m_pComponent_ != NULL && "ComponentManager::RemoveComponent() : Component is NULL");

		for (std::vector<Component *>::iterator it = m_Components.begin();
			it != m_Components.end();
			it++)
		{
			if ((*it) == m_pComponent_)
			{
				m_Components.erase(it);
				break;
			}			
		}		
	}

	/**
	 * 
	 */
	void ComponentManager::InitializeComponents()
	{
		for (size_t i=0; i<m_Components.size(); i++)
		{
			m_Components[i]->Initialize();
		}
	}

	/**
	 * 
	 */
	bool ComponentManager::HandleMessage( const Telegram& msg )
	{
		bool res = false;

		for (size_t i=0; i<m_Components.size(); i++)
		{
			res |= m_Components[i]->HandleMessage(msg);
		}

		return res;
	}

} // namespace CasaEngine
